package com.ocom.xfrecode.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.UnifiendPayUrl;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfRecordOrg;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.exposeapi.LargeScreenRequest;
import com.ocom.common.request.web.*;
import com.ocom.common.request.xfrecde.DeptReportVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.xfrecode.service.XfRecordOrgService;
import com.ocom.xfrecode.service.XfRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
public class TotalController{

    @Autowired
    private XfRecordService xfRecordService;

    @Autowired
    private XfRecordOrgService xfRecordOrgService;

    //查询每天各餐段汇总结果
    @PostMapping(UnifiendPayUrl.URL_dayTotalMealNo)
    public Result times(@RequestBody JSONObject jsonObject){
        try {
            List<EntityXfRecord> list=xfRecordService.dayTotalMealNo(jsonObject);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getMealNo());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum() != null ? entityXfRecord.getRefundNum() : 0);
                object.put("refundAmount",entityXfRecord.getRefundAmount() != null ? entityXfRecord.getRefundAmount() : 0);
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

  //查询每天各餐段汇总结果
  @PostMapping(UnifiendPayUrl.URL_dayTotalMealNoXM)
  public Result timesXM(@RequestBody JSONObject jsonObject){
    try {
      List<EntityXfRecord> list=xfRecordService.dayTotalMealNoXM(jsonObject);
      List<Map<String,Object>> reList=new ArrayList<>();
      for (EntityXfRecord entityXfRecord : list) {
        Map<String,Object> object=new HashMap<>();
        object.put("stime",entityXfRecord.getSTime());
        object.put("reportType",entityXfRecord.getMealNo());
        object.put("orderNum",entityXfRecord.getOrderNum());
        object.put("amount",entityXfRecord.getAmount());
        object.put("refundNum",entityXfRecord.getRefundNum() != null ? entityXfRecord.getRefundNum() : 0);
        object.put("refundAmount",entityXfRecord.getRefundAmount() != null ? entityXfRecord.getRefundAmount() : 0);
        reList.add(object);
      }
      return ResultUtil.success(reList);
    }catch (Exception e){
      log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
      return ResultUtil.error(ResultEnum.Err_4002);
    }
  }

    //查询每天各餐段汇总不是饭堂的结果
    @PostMapping(UnifiendPayUrl.URL_totalMealNoCanteenNo)
    public Result dayTotalMealNoCanteenNo(@RequestBody JSONObject jsonObject){
        try {
            List<EntityXfRecord> list=xfRecordService.dayTotalMealNoCanteenNo(jsonObject);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getReportType());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum());
                object.put("refundAmount",entityXfRecord.getRefundAmount());
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总不是饭堂的结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    //查询每天各支付方式汇总结果
    @PostMapping(UnifiendPayUrl.URL_dayTotalPayType)
    public Result dayTotalPayType(@RequestBody JSONObject jsonObject){
        try {
            List<EntityXfRecord> list=xfRecordService.dayTotalPayType(jsonObject);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getOpType());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum());
                object.put("refundAmount",entityXfRecord.getRefundAmount());
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

  //查询每天各支付方式汇总结果
  @PostMapping(UnifiendPayUrl.URL_dayTotalPayTypeXM)
  public Result dayTotalPayTypeXM(@RequestBody JSONObject jsonObject){
    try {
      List<EntityXfRecord> list=xfRecordService.dayTotalPayTypeXM(jsonObject);
      List<Map<String,Object>> reList=new ArrayList<>();
      for (EntityXfRecord entityXfRecord : list) {
        Map<String,Object> object=new HashMap<>();
        object.put("stime",entityXfRecord.getSTime());
        object.put("reportType",entityXfRecord.getOpType());
        object.put("orderNum",entityXfRecord.getOrderNum());
        object.put("amount",entityXfRecord.getAmount());
        object.put("refundNum",entityXfRecord.getRefundNum());
        object.put("refundAmount",entityXfRecord.getRefundAmount());
        reList.add(object);
      }
      return ResultUtil.success(reList);
    }catch (Exception e){
      log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
      return ResultUtil.error(ResultEnum.Err_4002);
    }
  }

    //查询每天各收款账户汇总结果
    @PostMapping(UnifiendPayUrl.URL_dayTotalAccount)
    public Result dayTotalAccount(@RequestBody JSONObject jsonObject){
        try {
            List<EntityXfRecord> list=xfRecordService.dayTotalAccount(jsonObject);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getReportType());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum());
                object.put("refundAmount",entityXfRecord.getRefundAmount());
                object.put("chargeNum",entityXfRecord.getChargeNum());
                object.put("chargeAmount",entityXfRecord.getChargeAmount());
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

  //查询每天各收款账户汇总结果
  @PostMapping(UnifiendPayUrl.URL_dayTotalAccountXM)
  public Result dayTotalAccountXM(@RequestBody JSONObject jsonObject){
    try {
      List<EntityXfRecord> list=xfRecordService.dayTotalAccountXM(jsonObject);
      List<Map<String,Object>> reList=new ArrayList<>();
      for (EntityXfRecord entityXfRecord : list) {
        Map<String,Object> object=new HashMap<>();
        object.put("stime",entityXfRecord.getSTime());
        object.put("reportType",entityXfRecord.getReportType());
        object.put("orderNum",entityXfRecord.getOrderNum());
        object.put("amount",entityXfRecord.getAmount());
        object.put("refundNum",entityXfRecord.getRefundNum());
        object.put("refundAmount",entityXfRecord.getRefundAmount());
        object.put("chargeNum",entityXfRecord.getChargeNum());
        object.put("chargeAmount",entityXfRecord.getChargeAmount());
        reList.add(object);
      }
      return ResultUtil.success(reList);
    }catch (Exception e){
      log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每天各餐段汇总结果",jsonObject,e);
      return ResultUtil.error(ResultEnum.Err_4002);
    }
  }

    //查询每月各餐段汇总结果
    @PostMapping(UnifiendPayUrl.URL_monthTotalMealNo)
    public Result monthTotalMealNo(@RequestBody JSONObject jsonObject){
        try {

            Calendar cal = Calendar.getInstance();
            Date date=new Date();//现在的日期
            cal.setTime(date);
            String[] arr=jsonObject.getString("summaryDate").split("-");
            Integer year=cal.get(Calendar.YEAR);//获取年
            Integer yearNew = Integer.valueOf(arr[0]);
            String start=yearNew+"01";
            String end= String.valueOf(yearNew);
            if (year<yearNew){
                return ResultUtil.error(ResultEnum.Err_4039);
            }else if (year>yearNew){
                end=end+"12";
            }else {
                Integer month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
                end=end+month;
            }
            List<EntityXfRecord> list=xfRecordService.monthTotalMealNo(jsonObject,start,end);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                boolean addBoolean=true;
                Map<String,Object> object=new HashMap<>();
                if (reList.size()>0){
                    for (Map<String, Object> map : reList) {
                        String STime= String.valueOf(map.get("stime"));
                        String reportType= String.valueOf(map.get("reportType"));

                        if (entityXfRecord.getSTime().equals(STime) && entityXfRecord.getReportType().equals(reportType)){
                            Integer orderNum= (Integer) map.get("orderNum");
                            Long amount= (Long) map.get("amount");
                            Integer refundNum= (Integer) map.get("refundNum");
                            Integer refundAmount= (Integer) map.get("refundAmount");

                            map.put("orderNum",entityXfRecord.getOrderNum()+orderNum);
                            map.put("amount",entityXfRecord.getAmount()+amount);
                            map.put("refundNum",entityXfRecord.getRefundNum()+refundNum);
                            map.put("refundAmount",entityXfRecord.getRefundAmount()+refundAmount);
                            addBoolean=false;
                        }
                    }
                }
                if (addBoolean){
                    object.put("stime",entityXfRecord.getSTime());
                    object.put("reportType",entityXfRecord.getReportType());
                    object.put("orderNum",entityXfRecord.getOrderNum());
                    object.put("amount",entityXfRecord.getAmount());
                    object.put("refundNum",entityXfRecord.getRefundNum());
                    object.put("refundAmount",entityXfRecord.getRefundAmount());
                    reList.add(object);
                }
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每月各餐段汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    @PostMapping(UnifiendPayUrl.URL_monthMealNoCanteenNo)
    public Result monthMealNoCanteenNo(@RequestBody JSONObject jsonObject){
        try {

            Calendar cal = Calendar.getInstance();
            Date date=new Date();//现在的日期
            cal.setTime(date);
            String[] arr=jsonObject.getString("summaryDate").split("-");
            Integer year=cal.get(Calendar.YEAR);//获取年
            Integer yearNew = Integer.valueOf(arr[0]);
            String start=yearNew+"01";
            String end= String.valueOf(yearNew);
            if (year<yearNew){
                return ResultUtil.error(ResultEnum.Err_4039);
            }else if (year>yearNew){
                end=end+"12";
            }else {
                Integer month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
                end=end+month;
            }
            List<EntityXfRecord> list=xfRecordService.monthMealNoCanteenNo(jsonObject,start,end);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                boolean addBoolean=true;
                Map<String,Object> object=new HashMap<>();
                if (reList.size()>0){
                    for (Map<String, Object> map : reList) {
                        String STime= String.valueOf(map.get("stime"));
                        String reportType= String.valueOf(map.get("reportType"));

                        if (entityXfRecord.getSTime().equals(STime) && entityXfRecord.getReportType().equals(reportType)){
                            Integer orderNum= (Integer) map.get("orderNum");
                            Long amount= (Long) map.get("amount");
                            Integer refundNum= (Integer) map.get("refundNum");
                            Integer refundAmount= (Integer) map.get("refundAmount");

                            map.put("orderNum",entityXfRecord.getOrderNum()+orderNum);
                            map.put("amount",entityXfRecord.getAmount()+amount);
                            map.put("refundNum",entityXfRecord.getRefundNum()+refundNum);
                            map.put("refundAmount",entityXfRecord.getRefundAmount()+refundAmount);
                            addBoolean=false;
                        }
                    }
                }
                if (addBoolean){
                    object.put("stime",entityXfRecord.getSTime());
                    object.put("reportType",entityXfRecord.getReportType());
                    object.put("orderNum",entityXfRecord.getOrderNum());
                    object.put("amount",entityXfRecord.getAmount());
                    object.put("refundNum",entityXfRecord.getRefundNum());
                    object.put("refundAmount",entityXfRecord.getRefundAmount());
                    reList.add(object);
                }
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每月各餐段汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    //查询每月各支付方式汇总结果
    @PostMapping(UnifiendPayUrl.URL_monthTotalPayType)
    public Result monthTotalPayType(@RequestBody JSONObject jsonObject){
        try {

            Calendar cal = Calendar.getInstance();
            Date date=new Date();//现在的日期
            cal.setTime(date);
            String[] arr=jsonObject.getString("summaryDate").split("-");
            Integer year=cal.get(Calendar.YEAR);//获取年
            Integer yearNew = Integer.valueOf(arr[0]);
            String start=yearNew+"01";
            String end= String.valueOf(yearNew);
            if (year<yearNew){
                return ResultUtil.error(ResultEnum.Err_4039);
            }else if (year>yearNew){
                end=end+"12";
            }else {
                Integer month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
                end=end+month;
            }
            List<EntityXfRecord> list=xfRecordService.monthTotalPayType(jsonObject,start,end);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getReportType());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum());
                object.put("refundAmount",entityXfRecord.getRefundAmount());
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】","查询每月各支付方式汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    // 查询每月各收款账户汇总结果
    @PostMapping(UnifiendPayUrl.URL_monthTotalAccount)
    public Result monthTotalAccount(@RequestBody JSONObject jsonObject){
        try {

            Calendar cal = Calendar.getInstance();
            Date date=new Date();//现在的日期
            cal.setTime(date);
            String[] arr=jsonObject.getString("summaryDate").split("-");
            Integer year=cal.get(Calendar.YEAR);//获取年
            Integer yearNew = Integer.valueOf(arr[0]);
            String start=yearNew+"01";
            String end= String.valueOf(yearNew);
            if (year<yearNew){
                return ResultUtil.error(ResultEnum.Err_4039);
            }else if (year>yearNew){
                end=end+"12";
            }else {
                Integer month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
                end=end+month;
            }
            List<EntityXfRecord> list=xfRecordService.monthTotalAccount(jsonObject,start,end);
            List<Map<String,Object>> reList=new ArrayList<>();
            for (EntityXfRecord entityXfRecord : list) {
                Map<String,Object> object=new HashMap<>();
                object.put("stime",entityXfRecord.getSTime());
                object.put("reportType",entityXfRecord.getReportType());
                object.put("orderNum",entityXfRecord.getOrderNum());
                object.put("amount",entityXfRecord.getAmount());
                object.put("refundNum",entityXfRecord.getRefundNum());
                object.put("refundAmount",entityXfRecord.getRefundAmount());
                reList.add(object);
            }
            return ResultUtil.success(reList);
        }catch (Exception e){
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】"," 查询每月各收款账户汇总结果",jsonObject,e);
            return ResultUtil.error(ResultEnum.Err_4002);
        }
    }

    /**
     *@Description:钱包余额
     * @author lu
     * @param comId
     * @param month
     * @return com.ocom.common.resp.Result
     * @date 2022/10/14 13:58
     */
    @PostMapping(UnifiendPayUrl.URL_walletBalance)
    public Result walletBalance(Long comId,String month,
                                @RequestParam(value = "subAccount",required = false,defaultValue = "0") Integer subAccount){
        try {
            String nowMonth= DateUtils.getStrDate(new Date(),"yyyy-MM");
            Map<String,Object> map=new HashMap<>();
            if (month==null || nowMonth.equals(month)){
                if (month==null){
                    month=nowMonth;
                }
                SimpleDateFormat simpleDateFormats = new SimpleDateFormat("dd");
                String firstDate=DateUtils.getFirstDate("yyyy-MM-dd");
                String newDay=simpleDateFormats.format(new Date());
                Date yesterdayD=null;
                //判断是否是1号
                if (newDay.equals("01")){
                    map.put("recharge",walletBalances(comId,month,1,null,null,subAccount));
                    map.put("subsidy",walletBalances(comId,month,2,null,null,subAccount));
                    map.put("endDate",DateUtils.getendDate(DateUtils.getDate(DateUtils.getLastMonth(),"yyyy-MM"),"yyyy-MM-dd"));
                }else {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date today = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);
                    String yesterday = simpleDateFormat.format(today);//获取昨天日期
                    yesterday =yesterday+" 23:59:59";
                    yesterdayD=DateUtils.getDate(yesterday,DateUtils.YYYY_MM_DD_HH_MM_SS);

                    firstDate=firstDate+" 00:00:00";
                    Date firstDateD=DateUtils.getDate(firstDate,DateUtils.YYYY_MM_DD_HH_MM_SS);
                    map.put("recharge",walletBalances(comId,month,1,yesterdayD,firstDateD,subAccount));
                    map.put("subsidy",walletBalances(comId,month,2,yesterdayD,firstDateD,subAccount));
                    map.put("endDate",DateUtils.getStrDate(yesterdayD,"yyyy-MM-dd"));
                }

            }else {
                map.put("recharge",walletBalances(comId,month,1,null,null,subAccount));
                map.put("subsidy",walletBalances(comId,month,2,null,null,subAccount));
                map.put("endDate",DateUtils.getendDate(DateUtils.getDate(month,"yyyy-MM"),"yyyy-MM-dd"));
            }
            return ResultUtil.success(map);
        }catch (Exception e){
            log.info("钱包余额异常:"+e);
            return ResultUtil.error(ResultEnum.Err_900);
        }

    }

    private Map<String,Integer> walletBalances(Long comId,String month,Integer types,Date yesterdayD,Date firstDateD,
                                               @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount)throws Exception{
        List<EntityXfRecord> list=null;
        Map<String,Integer> map=new HashMap<>();
        if (yesterdayD !=null){
            list=xfRecordService.walletBalanceFirstDate(comId,yesterdayD,firstDateD,month,types,subAccount);
        }else {
            list=xfRecordService.walletBalance(comId,month,types,subAccount);
        }
        int openBalance=0;
        int closeBalance=0;
        int consumeAmount=0;
        int consumeNumber=0;
        int rechargeAmount=0;
        int rechargeNumber=0;
        int settleAmount=0;
        int settleNumber=0;
        for (EntityXfRecord entityXfRecord : list) {
            openBalance=openBalance+entityXfRecord.getOpenBalance();
            closeBalance=closeBalance+entityXfRecord.getCloseBalance();
            consumeAmount=consumeAmount+entityXfRecord.getConsumeAmount();
            consumeNumber=consumeNumber+entityXfRecord.getConsumeNumber();
            rechargeAmount=rechargeAmount+entityXfRecord.getRechargeAmount();
            rechargeNumber=rechargeNumber+entityXfRecord.getRechargeNumber();
            settleAmount=settleAmount+entityXfRecord.getSettleAmount();
            settleNumber=settleNumber+entityXfRecord.getSettleNumber();
        }

        map.put("openBalance",openBalance);
        map.put("closeBalance",closeBalance);
        map.put("consumeAmount",-consumeAmount);
        map.put("consumeNumber",consumeNumber);
        map.put("rechargeAmount",rechargeAmount);
        map.put("rechargeNumber",rechargeNumber);
        map.put("settleAmount",settleAmount);
        map.put("settleNumber",settleNumber);
        return map;
    }

    /**
     *@Description:补贴钱包日报
     * @author lu
     * @param comId
     * @param endDate
     * @return com.ocom.common.resp.Result
     * @date 2022/10/17 15:43
     */
    @PostMapping(UnifiendPayUrl.URL_subsidyDaily)
    public Result subsidyDaily(Long comId,String endDate,
                               @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(endDate,"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.subsidyDaily(comId,endDate,isLastDayOfMonth,subAccount);
        } catch (Exception e) {
           e.printStackTrace();
           log.info("补贴钱包日报异常:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("date",entityXfRecord.getDate());
            objectMap.put("consumeAmount",entityXfRecord.getConsumeAmount());
            objectMap.put("consumeNumber",entityXfRecord.getConsumeNumber());
            objectMap.put("consCancelAmount",entityXfRecord.getConsCancelAmount());
            objectMap.put("consCancelNumber",entityXfRecord.getConsCancelNumber());
            objectMap.put("rechargeAmount",entityXfRecord.getRechargeAmount());
            objectMap.put("rechargeNumber",entityXfRecord.getRechargeNumber());
            objectMap.put("settleAmount",entityXfRecord.getSettleAmount());
            objectMap.put("settleNumber",entityXfRecord.getSettleNumber());
            retList.add(objectMap);
        }
        map.put("daily",list);
        return ResultUtil.success(retList);
    }

    /**
     *@Description:现金钱包日报
     * @author lu
     * @param comId
     * @param endDate
     * @return com.ocom.common.resp.Result
     * @date 2022/10/17 16:53
     */
    @PostMapping(UnifiendPayUrl.URL_rechargeDaily)
    public Result rechargeDaily(Long comId,String endDate,
                                @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(endDate,"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.rechargeDaily(comId,endDate,isLastDayOfMonth,subAccount);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("现金钱包日报:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("date",entityXfRecord.getDate());
            objectMap.put("consumeAmount",entityXfRecord.getConsumeAmount());
            objectMap.put("consumeNumber",entityXfRecord.getConsumeNumber());
            objectMap.put("consCancelAmount",entityXfRecord.getConsCancelAmount());
            objectMap.put("consCancelNumber",entityXfRecord.getConsCancelNumber());
            objectMap.put("rechargeAmount",entityXfRecord.getRechargeAmount());
            objectMap.put("rechargeNumber",entityXfRecord.getRechargeNumber());
            objectMap.put("cashAmount",entityXfRecord.getCashAmount());
            objectMap.put("cashNumber",entityXfRecord.getCashNumber());
            objectMap.put("cashoutAmount",entityXfRecord.getCashoutAmount());
            objectMap.put("cashoutNumber",entityXfRecord.getCashoutNumber());
            objectMap.put("settleAmount",entityXfRecord.getSettleAmount());
            objectMap.put("settleNumber",entityXfRecord.getSettleNumber());
            retList.add(objectMap);
        }
        map.put("daily",list);
        return ResultUtil.success(retList);
    }



    /**
     *@Description:现金月报
     * @author lu
     * @param comId
     * @param endDate
     * @return com.ocom.common.resp.Result
     * @date 2022/10/20 13:54
     */
    @PostMapping(UnifiendPayUrl.URL_cashMonthly)
    public Result cashMonthly(Long comId,String endDate,
                              @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount,
                              @RequestParam(value = "merchIds",required = false,defaultValue = "")String merchIds){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(endDate,"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.cashMonthly(comId,endDate,isLastDayOfMonth,subAccount,merchIds);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("现金月报:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            if (entityXfRecord.getCashAmount() !=0 || entityXfRecord.getCashNumber()!=0 ||
                    entityXfRecord.getCashoutAmount() !=0 || entityXfRecord.getCashoutNumber() !=0){
                Map<String,Object> objectMap=new HashMap<>();
                if (entityXfRecord.getMngUserId()==0 && entityXfRecord.getDeviceNo()!=null){
                    objectMap.put("type",2);
                    objectMap.put("deviceNo",entityXfRecord.getDeviceNo());
                    objectMap.put("name",entityXfRecord.getDeviceName());

                }else if (entityXfRecord.getMngUserId()==0 && entityXfRecord.getDeviceNo() ==null){
                    objectMap.put("type",1);
                    objectMap.put("mngUserId",0);
                    objectMap.put("name","未知管理员");
                }else {
                    objectMap.put("type",1);
                    objectMap.put("mngUserId",entityXfRecord.getMngUserId());
                    objectMap.put("name",entityXfRecord.getAdminName());
                }
                objectMap.put("cashNumber",entityXfRecord.getCashNumber());
                objectMap.put("cashAmount",entityXfRecord.getCashAmount());
                objectMap.put("cashoutNumber",entityXfRecord.getCashoutNumber());
                objectMap.put("cashoutAmount",entityXfRecord.getCashoutAmount());
                retList.add(objectMap);
            }
        }
        map.put("monthly",list);
        return ResultUtil.success(retList);
    }

    /**
     *@Description:现金日报
     * @author lu
     * @param cashDailyRequest
     * @return com.ocom.common.resp.Result
     * @date 2022/10/21 10:38
     */
    @PostMapping(UnifiendPayUrl.URL_cashDaily)
    public Result cashDaily(@Validated @RequestBody CashDailyRequest cashDailyRequest){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(cashDailyRequest.getEndDate(),"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.cashDaily(cashDailyRequest,isLastDayOfMonth);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("现金日报:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("date",entityXfRecord.getDate());
            objectMap.put("cashNumber",entityXfRecord.getCashNumber());
            objectMap.put("cashAmount",entityXfRecord.getCashAmount());
            objectMap.put("cashoutNumber",entityXfRecord.getCashoutNumber());
            objectMap.put("cashoutAmount",entityXfRecord.getCashoutAmount());
            retList.add(objectMap);
        }
        map.put("daily",list);
        return ResultUtil.success(retList);
    }


    /**
     *@Description:商户消费月报
     * @author lu
     * @param comId
     * @param endDate
     * @return com.ocom.common.resp.Result
     * @date 2022/10/21 13:35
     */
    @PostMapping(UnifiendPayUrl.URL_merchMonthly)
    public Result merchMonthly(Long comId, String endDate,
                               @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount,
                               @RequestParam(value = "merchIds",required = false,defaultValue = "")String merchIds){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(endDate,"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.merchMonthly(comId,endDate,isLastDayOfMonth,subAccount,merchIds);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("现金日报:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("merchId",entityXfRecord.getMerchId());
            objectMap.put("merchName",entityXfRecord.getMerchName());
            objectMap.put("consNumber",entityXfRecord.getConsNumber());
            objectMap.put("chargeAmount",-entityXfRecord.getChargeAmount());
            objectMap.put("subAmount",-entityXfRecord.getSubAmount());
            objectMap.put("consAmount",-entityXfRecord.getConsAmount());
            retList.add(objectMap);
        }
        map.put("monthly",list);
        return ResultUtil.success(retList);
    }

    @PostMapping(UnifiendPayUrl.URL_merchDaily)
    public Result merchDaily(Long comId,String endDate,Integer merchId,
                             @RequestParam(value = "subAccount",required = false,defaultValue = "0")Integer subAccount){
        boolean isLastDayOfMonth=DateUtils.isLastDayOfMonth(endDate,"yyyy-MM-dd");
        Map<String,Object> map=new HashMap<>();
        List<EntityXfRecord> list = null;
        try {
            list = xfRecordService.merchDaily(comId,endDate,isLastDayOfMonth,merchId,subAccount);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("现金日报:"+e);
        }
        List<Map<String,Object>> retList=new ArrayList<>();
        for (EntityXfRecord entityXfRecord : list) {
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("date",entityXfRecord.getDate());
            objectMap.put("consumeAmount",-entityXfRecord.getConsumeAmount());
            objectMap.put("consumeNumber",entityXfRecord.getConsumeNumber());
            objectMap.put("consCancelAmount",entityXfRecord.getConsCancelAmount());
            objectMap.put("consCancelNumber",entityXfRecord.getConsCancelNumber());
            objectMap.put("chargeAmount",-entityXfRecord.getChargeAmount());
            objectMap.put("subAmount",-entityXfRecord.getSubAmount());
            retList.add(objectMap);
        }
        map.put("daily",list);
        return ResultUtil.success(retList);
    }

    /**
     *@Description:获取人员消费汇总报表（getConsPerReports）
     * @author lu
     * @param getConsPerReportsRequest
     * @return com.ocom.common.resp.Result
     * @date 2023/2/17 14:34
     */
    @PostMapping(UnifiendPayUrl.URL_getConsPerReports)
    public Result getConsPerReports(@Validated @RequestBody GetConsPerReportsRequest getConsPerReportsRequest){
        try {
            Page<EntityXfRecord> list=xfRecordService.getConsPerReports(getConsPerReportsRequest);
            List<Map<String,Object>> mapList=new ArrayList<>();
            for (EntityXfRecord record : list.getRecords()) {
                Map<String,Object> object=new HashMap<>();
                object.put("sTime",record.getSTime());
                object.put("deptId",record.getDeptId());
                object.put("deptName",record.getDeptName());
                object.put("pCode",record.getPCode());
                object.put("pName",record.getPName());
                object.put("cardNo",record.getCardNo());
                object.put("allAmount",-record.getAllAmount());
                object.put("allDiscount",record.getAllDiscount());
                object.put("allRealAmount",-record.getAllRealAmount());
                object.put("allTimes",record.getAllTimes());
                object.put("dkAmount",-record.getDkAmount());
                object.put("dkTimes",record.getDkTimes());
                object.put("xjAmount",-record.getXjAmount());
                object.put("btAmount",-record.getBtAmount());
                object.put("yhqAmount",record.getYhqAmount());
                object.put("xnzhTimes",record.getXnzhTimes());
                object.put("jcAmount",-record.getJcAmount());
                object.put("jcTimes",record.getJcTimes());
                mapList.add(object);
            }
            Map<String,Object> object=new HashMap<>();
            object.put("total",list.getTotal());
            object.put("list",mapList);
            return ResultUtil.success(object);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_900);
        }
    }

    /**
     *@Description:获取部门消费汇总报表
     * @author lu
     * @param getConsDeptReportsRequest
     * @return com.ocom.common.resp.Result
     * @date 2023/2/22 9:10
     */
    @PostMapping(UnifiendPayUrl.URL_getConsDeptReports)
    public Result getConsDeptReports(@Validated @RequestBody GetConsDeptReportsRequest getConsDeptReportsRequest){
        try {
            List<EntityXfRecord> list=xfRecordService.getConsDeptReports(getConsDeptReportsRequest);
            Map<String,Object> returnMap=new HashMap<>();
            List<DeptReportVo> mapList=new ArrayList<>();
            if (getConsDeptReportsRequest.getSize()!=-1 && getConsDeptReportsRequest.getPage() !=-1){
                PageInfo<EntityXfRecord> getConsDeptReportsPageInfo = new PageInfo<>(list);
                for (EntityXfRecord entityXfRecord : getConsDeptReportsPageInfo.getList()) {
                    DeptReportVo deptReportVo =new DeptReportVo();
                    deptReportVo.setSTime(entityXfRecord.getSTime());
                    deptReportVo.setMealNo(entityXfRecord.getMealNo());
                    deptReportVo.setDeptId(entityXfRecord.getDeptId());
                    deptReportVo.setDeptName(entityXfRecord.getDeptName());
                    deptReportVo.setAllAmount(entityXfRecord.getAllAmount());
                    deptReportVo.setAllDiscount(entityXfRecord.getAllDiscount());
                    deptReportVo.setAllRealAmount(entityXfRecord.getAllRealAmount());
                    deptReportVo.setAllTimes(entityXfRecord.getAllTimes());
                    deptReportVo.setDkAmount(entityXfRecord.getDkAmount());
                    deptReportVo.setDkTimes(entityXfRecord.getDkTimes());
                    deptReportVo.setXjAmount(entityXfRecord.getXjAmount());
                    deptReportVo.setBtAmount(entityXfRecord.getBtAmount());
                    deptReportVo.setYhqAmount(entityXfRecord.getYhqAmount());
                    deptReportVo.setXnzhTimes(entityXfRecord.getXnzhTimes());
                    deptReportVo.setJcAmount(entityXfRecord.getJcAmount());
                    deptReportVo.setJcTimes(entityXfRecord.getJcTimes());
                    mapList.add(deptReportVo);
                }
                returnMap.put("total",getConsDeptReportsPageInfo.getTotal());
            }else {
                for (EntityXfRecord entityXfRecord : list) {
                    DeptReportVo deptReportVo =new DeptReportVo();
                    deptReportVo.setSTime(entityXfRecord.getSTime());
                    deptReportVo.setMealNo(entityXfRecord.getMealNo());
                    deptReportVo.setDeptId(entityXfRecord.getDeptId());
                    deptReportVo.setDeptName(entityXfRecord.getDeptName());
                    deptReportVo.setAllAmount(entityXfRecord.getAllAmount());
                    deptReportVo.setAllDiscount(entityXfRecord.getAllDiscount());
                    deptReportVo.setAllRealAmount(entityXfRecord.getAllRealAmount());
                    deptReportVo.setAllTimes(entityXfRecord.getAllTimes());
                    deptReportVo.setDkAmount(entityXfRecord.getDkAmount());
                    deptReportVo.setDkTimes(entityXfRecord.getDkTimes());
                    deptReportVo.setXjAmount(entityXfRecord.getXjAmount());
                    deptReportVo.setBtAmount(entityXfRecord.getBtAmount());
                    deptReportVo.setYhqAmount(entityXfRecord.getYhqAmount());
                    deptReportVo.setXnzhTimes(entityXfRecord.getXnzhTimes());
                    deptReportVo.setJcAmount(entityXfRecord.getJcAmount());
                    deptReportVo.setJcTimes(entityXfRecord.getJcTimes());
                    mapList.add(deptReportVo);
                }
                returnMap.put("total",list.size());
            }
            returnMap.put("list",mapList);
            return ResultUtil.success(returnMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_900);
        }
    }

    @PostMapping(UnifiendPayUrl.URL_getAccDiscountReports)
    public Result getAccDiscountReports(@Validated @RequestBody AccDiscountReportsOnShowRequest request){

        try {
            List<EntityXfRecord> list = xfRecordService.getAccDiscountReports(request);
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_900);
        }

    }

    @PostMapping(UnifiendPayUrl.URL_getConsMerchReports)
    public Result getConsMerchReports(Long comId,String startTime,String endTime,String merchIds){
        try {
            Date startDate = DateUtil.parseDate(startTime);
            Date endDate = DateUtil.parse(endTime);
            long betweenMonth = DateUtil.betweenMonth(startDate,endDate,true);
//            List<Map<String,Object>> mapList=new ArrayList<>();
            Map<Long,Map<String,Object>> objectMap = new HashMap<>();
            for(long i=0;i<=betweenMonth; i++){
                String startTimeA;
                String endTimeA;
                if(betweenMonth == 0){
                    startTimeA = startTime;
                    endTimeA = endTime;
                }else{
                    startTimeA = DateUtil.formatDate(DateUtil.beginOfMonth(DateUtil.offsetMonth(startDate,(int) i)));
                    endTimeA = DateUtil.formatDate(DateUtil.endOfMonth(startDate));
                    if(i == 0){
                        startTimeA =  startTime;
                    } else if (i == betweenMonth) {
                        endTimeA = endTime;
                    }
                }

            List<EntityXfRecord> list=xfRecordService.getConsMerchReports(comId,startTimeA,endTimeA,merchIds);

                for (EntityXfRecord entityXfRecord : list) {
//                    Map<String,Object> object=new HashMap<>();
//                    object.put("merchId",entityXfRecord.getMerchId());
//                    object.put("merchAmount",-entityXfRecord.getMerchAmount());
//                    object.put("merchNumber",entityXfRecord.getMerchNumber());
//                    object.put("merchConsAmount",-entityXfRecord.getMerchConsAmount());
//                    object.put("merchDiscount",entityXfRecord.getMerchDiscount());
//                    object.put("cardAmount",-entityXfRecord.getCardAmount());
//                    object.put("cardNumber",entityXfRecord.getCardNumber());
//                    object.put("timesAmount",-entityXfRecord.getTimesAmount());
//                    object.put("timesNumber",entityXfRecord.getTimesNumber());
//                    object.put("days",entityXfRecord.getAmount1());
//                    mapList.add(object);

                    Map<String,Object> objectA= objectMap.get(entityXfRecord.getMerchId());
                    if(ObjectUtil.isEmpty(objectA)){
                        objectA = new HashMap<>();
                    }
                    objectA.put("merchId",entityXfRecord.getMerchId());
                    objectA.put("merchAmount",ObjectUtil.isEmpty(objectA.get("merchAmount"))?-entityXfRecord.getMerchAmount():Integer.parseInt(objectA.get("merchAmount").toString()) - entityXfRecord.getMerchAmount());
                    objectA.put("merchNumber",ObjectUtil.isEmpty(objectA.get("merchNumber"))?entityXfRecord.getMerchNumber():Integer.parseInt(objectA.get("merchNumber").toString())+ entityXfRecord.getMerchNumber());
                    objectA.put("merchConsAmount",ObjectUtil.isEmpty(objectA.get("merchConsAmount"))?-entityXfRecord.getMerchConsAmount():Integer.parseInt(objectA.get("merchConsAmount").toString())- entityXfRecord.getMerchConsAmount());
                    objectA.put("merchDiscount",ObjectUtil.isEmpty(objectA.get("merchDiscount"))?entityXfRecord.getMerchDiscount():Integer.parseInt(objectA.get("merchDiscount").toString())+ entityXfRecord.getMerchDiscount());
                    objectA.put("cardAmount",ObjectUtil.isEmpty(objectA.get("cardAmount"))?-entityXfRecord.getCardAmount():Integer.parseInt(objectA.get("cardAmount").toString())- entityXfRecord.getCardAmount());
                    objectA.put("cardNumber",ObjectUtil.isEmpty(objectA.get("cardNumber"))?entityXfRecord.getCardNumber():Integer.parseInt(objectA.get("cardNumber").toString())+ entityXfRecord.getCardNumber());
                    objectA.put("timesAmount",ObjectUtil.isEmpty(objectA.get("timesAmount"))?-entityXfRecord.getTimesAmount():Integer.parseInt(objectA.get("timesAmount").toString())- entityXfRecord.getTimesAmount());
                    objectA.put("timesNumber",ObjectUtil.isEmpty(objectA.get("timesNumber"))?entityXfRecord.getTimesNumber():Integer.parseInt(objectA.get("timesNumber").toString())+ entityXfRecord.getTimesNumber());
                    objectA.put("days",ObjectUtil.isEmpty(objectA.get("days"))?entityXfRecord.getAmount1():Integer.parseInt(objectA.get("days").toString())+ entityXfRecord.getAmount1());

                    objectMap.put(entityXfRecord.getMerchId(),objectA);


                }
            }

            Map<String,Object> object=new HashMap<>();
//            object.put("list",mapList);
            object.put("list",objectMap.values());
            return ResultUtil.success(object);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_900);
        }
    }


    @PostMapping(UnifiendPayUrl.Url_yesterdayStudentMealRate)
    public Result yesterdayStudentMealRate(@RequestBody LargeScreenRequest request){
        List<EntityXfRecordOrg> xfRecordOrgList = xfRecordOrgService.yesterdayStudentMealRate(request);
        if(xfRecordOrgList==null || xfRecordOrgList.size()==0){
            return ResultUtil.error(ResultEnum.Err_1001);
        }
        return ResultUtil.success(xfRecordOrgList);
    }


    @PostMapping(UnifiendPayUrl.URL_getPointMealPre)
    public Result getPointMealPre(@RequestBody GetPointMealPreReportsRequest request)  {
        return ResultUtil.success(xfRecordService.getPointMealPre(request));
    }



    @PostMapping(UnifiendPayUrl.URL_getPointMealSend)
	public Result getPointMealSend(@RequestBody GetPointMealSendReportsRequest request) throws Exception {
		return ResultUtil.success(xfRecordService.getPointMealSend(request));
	}
}
